package com.applink.sell_proof.fragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.applink.sell_proof.BasePagerActivity;
import com.applink.sell_proof.QuizDetail;
import com.applink.sell_proof.QuizExpiredDetail;
import com.applink.sell_proof.QuizResult;
import com.applink.sell_proof.R;
import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.builder.QuizBuilder;
import com.applink.sell_proof.constant.Constant;
import com.applink.sell_proof.constant.IntentKey;
import com.applink.sell_proof.database.EMarketingContentProvider;
import com.applink.sell_proof.database.table.QuizDBHelper;
import com.applink.sell_proof.model.Quiz;
import com.applink.sell_proof.util.Utility;

public class QuizLifeFragment extends SherlockFragment implements
		LoaderCallbacks<Cursor>, OnEditorActionListener, OnScrollListener {
	public static final String TAG = "QUIZ_FRAGMENT";
	protected ViewGroup mLayout;
	protected QuizBuilder mQuizBuilder;
	protected View mHeaderCurrentQuiz;
	protected View mHeaderPreviousQuiz;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mLayout == null) {
			mLayout = (ViewGroup) inflater.inflate(R.layout.all_quiz, null,
					false);
		} else {
			if (mLayout.getParent() != null) {
				((ViewGroup) mLayout.getParent()).removeView(mLayout);
			}
		}
		((ListView) mLayout.findViewById(android.R.id.list))
				.setOnScrollListener(this);

		mHeaderPreviousQuiz = LayoutInflater.from(getActivity()).inflate(
				R.layout.header_previous_quiz, null);
		mHeaderCurrentQuiz = LayoutInflater.from(getActivity()).inflate(
				R.layout.header_current_quiz, null);
		((ListView) mLayout.findViewById(android.R.id.list)).addHeaderView(
				mHeaderCurrentQuiz, null, false);
		((ListView) mLayout.findViewById(android.R.id.list)).addHeaderView(
				mHeaderPreviousQuiz, null, false);
		mHeaderCurrentQuiz.findViewById(R.id.current_quiz).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						Quiz quiz = (Quiz) v.getTag();
						Intent intent;
						// check expired
						if (System.currentTimeMillis() > quiz.getEndDate()) {
							if (quiz.isSubmitted()) {
								intent = new Intent(getActivity(),
										QuizResult.class);
								intent.putExtra(Constant.KEY_QUIZ, quiz);
							} else {
								intent = new Intent(getActivity(),
										QuizExpiredDetail.class);
							}
						} else {
							if (quiz.isSubmitted()) {
								intent = new Intent(getActivity(),
										QuizExpiredDetail.class);
							} else {
								intent = new Intent(getActivity(),
										QuizDetail.class);
							}
						}
						int indexActivity = ((BasePagerActivity) getActivity())
								.getActivityIndex();
						intent.putExtra(IntentKey.ACTIVITY_NAME, indexActivity);
						intent.putExtra(Constant.KEY_QUIZ_ID, quiz.getId());
						getActivity().startActivity(intent);
					}
				});
		setHasOptionsMenu(true);

		return mLayout;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.menu_tip, menu);
		MenuItem search_bar = menu.findItem(R.id.search_bar);
		EditText searchBox = (EditText) search_bar.getActionView()
				.findViewById(R.id.et_search_bar);
		searchBox.setOnEditorActionListener(this);
		DataHelper.getInstance().getAllQuiz(1, 100, getCategory());
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getActivity().getSupportLoaderManager().initLoader(1, null, this);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
		return new CursorLoader(getActivity(),
				EMarketingContentProvider.QUIZ_CONTENT_URI, null,
				QuizDBHelper.QUIZ_CATEGORY + "=?",
				new String[] { Integer.toString(getCategory().toInt()) },
				QuizDBHelper.END_DATE + " DESC");
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		if (Utility.checkQuiz == true) {
			if (data != null && loader.getId() == 1) {
				List<Quiz> quizs = new ArrayList<Quiz>();
				if (data.moveToFirst()) {
					mHeaderCurrentQuiz.setVisibility(View.VISIBLE);
					String endDate = DateFormat.getDateFormat(getActivity())
							.format(new Date((data.getLong(data
									.getColumnIndex(QuizDBHelper.END_DATE)))));
					((TextView) mHeaderCurrentQuiz
							.findViewById(R.id.quiz_end_date)).setText(endDate);
					((TextView) mHeaderCurrentQuiz.findViewById(R.id.quiz_name))
							.setText(data.getString(data
									.getColumnIndex(QuizDBHelper.NAME)));
					((TextView) mHeaderCurrentQuiz
							.findViewById(R.id.quiz_description)).setText(data
							.getString(data
									.getColumnIndex(QuizDBHelper.DESCRIPTION)));
					Quiz quizTag = new Quiz();
					quizTag.setId(data.getLong(data
							.getColumnIndex(QuizDBHelper.QUIZ_ID)));
					quizTag.setSubmitted(data.getInt(data
							.getColumnIndex(QuizDBHelper.SUBMITTED)) == 1);
					quizTag.setEndDate(data.getLong(data
							.getColumnIndex(QuizDBHelper.END_DATE)));
					quizTag.setName(data.getString(data
							.getColumnIndex(QuizDBHelper.NAME)));
					quizTag.setDescription(data.getString(data
							.getColumnIndex(QuizDBHelper.DESCRIPTION)));

					if (quizTag.isSubmitted()) {
						((TextView) mHeaderCurrentQuiz
								.findViewById(R.id.quiz_stage))
								.setText(getActivity().getString(
										R.string.quiz_participated));
					} else if (System.currentTimeMillis() > quizTag
							.getEndDate()) {
						((TextView) mHeaderCurrentQuiz
								.findViewById(R.id.quiz_stage))
								.setText(getActivity().getString(
										R.string.quiz_close));
					} else {
						((TextView) mHeaderCurrentQuiz
								.findViewById(R.id.quiz_stage))
								.setText(getActivity().getString(
										R.string.quiz_open));
					}

					mHeaderCurrentQuiz.findViewById(R.id.current_quiz).setTag(
							quizTag);

					if (data.moveToNext()) {
						do {
							Quiz quiz = new Quiz();
							quiz.setStartDate(data.getLong(data
									.getColumnIndex(QuizDBHelper.START_DATE)));
							quiz.setEndDate(data.getLong(data
									.getColumnIndex(QuizDBHelper.END_DATE)));
							quiz.setName(data.getString(data
									.getColumnIndex(QuizDBHelper.NAME)));
							quiz.setDescription(data.getString(data
									.getColumnIndex(QuizDBHelper.DESCRIPTION)));
							quiz.setId(data.getLong(data
									.getColumnIndex(QuizDBHelper.QUIZ_ID)));
							quiz.setSubmitted(data.getInt(data
									.getColumnIndex(QuizDBHelper.SUBMITTED)) == 1);

							quizs.add(quiz);
						} while (data.moveToNext());
					}
					// if(quizs.size() > 0) {
					// mHeaderPreviousQuiz.setVisibility(View.VISIBLE);
					mQuizBuilder = new QuizBuilder(getActivity(), mLayout);
					mQuizBuilder.setData(quizs);
					// } else {
					// mHeaderPreviousQuiz.setVisibility(View.INVISIBLE);
					// DataHelper.getInstance().getAllQuiz(0, 10,getCategory());
					// }
				} else {
					//DataHelper.getInstance().getAllQuiz(1, 100, getCategory());
				}
				Log.e(TAG, "on quiz " + getCategory().toString()
						+ " load finish " + loader.getId() + " data size "
						+ quizs.size());
			}
		}

	}

	protected Quiz.Category getCategory() {
		return Quiz.Category.LIFE_STYLE;
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (actionId == EditorInfo.IME_ACTION_SEARCH) {
			SearchQuiz searchResult = (SearchQuiz) getActivity()
					.getSupportFragmentManager().findFragmentByTag(
							SearchQuiz.TAG);
			if (searchResult == null)
				searchResult = new SearchQuiz();
			FragmentTransaction transaction = getActivity()
					.getSupportFragmentManager().beginTransaction();
			transaction.replace(R.id.main_container, searchResult,
					SearchQuiz.TAG);
			transaction.addToBackStack(null);
			transaction.commit();
			searchResult.searchQuiz(v.getText().toString(), getCategory());
			InputMethodManager imm = (InputMethodManager) getActivity()
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
			return true;
		}
		return false;
	}

	protected int mVisibleItem;
	protected int mFirstVisibleItem;

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		mVisibleItem = visibleItemCount;
		mFirstVisibleItem = firstVisibleItem;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (scrollState == SCROLL_STATE_IDLE
				&& mVisibleItem > 0
				&& mFirstVisibleItem + mVisibleItem >= mQuizBuilder.getData()
						.size()) {
			//DataHelper.getInstance().getAllQuiz(1, 100, getCategory()); // offset
																		// start
																		// from
																		// 1.
		}

	}

}
